/*
 * @Author: wuqingchun
 * @Date: 2024-09-27 08:50:52
 * @Description: 
 * @LastEditors: wuqingchun
 * @LastEditTime: 2024-10-01 16:43:29
 */
#include <cstdio>
#include <cstdlib>

#include "chat_msg.h"
#include "chat_client.h"


CChatClient::CChatClient(const char* pcServerHost, uint16_t usPort):
    m_objSession(pcServerHost, usPort)
{

}

CChatClient::~CChatClient()
{

}

void CChatClient::Run()
{
    CHAT_CLIENT_COMMAND_E enCmd = CHAT_CLIENT_CMD_MAX;

    m_bRunning = true;

    while (m_bRunning)
    {
        enCmd = __GetCommand();

        __DispatchCommand(enCmd);
    }
    
}

void CChatClient::__WaitInput(const char* pcPrompt, char* pcBuff, size_t ulBufLen)
{

    printf("%s: ", pcPrompt);
    char* pcLine = pcBuff;
    size_t ulLen = ulBufLen;
    ssize_t lResult = 0;
    do
    {
        lResult = getline(&pcLine, &ulLen, stdin);
    } while (lResult <= 1);

    // 删除换行符
    pcLine[lResult-1] = '\0';
}


CHAT_CLIENT_COMMAND_E CChatClient::__GetCommand()
{
    char szLine[1024];
    CHAT_CLIENT_COMMAND_E enCmd = CHAT_CLIENT_CMD_MAX;
    static const char* apcMenu[CHAT_CLIENT_CMD_MAX] = 
    {
        "Show this help",
        "User login",
        "User logout",
        "User register",
        "Exit"
    };

    printf("================Simple Chatroom=================\n");
    for (int i = 0; i < CHAT_CLIENT_CMD_MAX; i++)
    {
        printf("[%2d] - %s\n", i, apcMenu[i]);
    }
    printf("================Simple Chatroom=================\n");

    __WaitInput("Enter your commond", szLine, sizeof(szLine));

    
    if (szLine[0] > '9' || szLine[0] < '0')
    {
        return CHAT_CLIENT_CMD_MAX;
    }

    return (CHAT_CLIENT_COMMAND_E)atoi(szLine);
}

void CChatClient::__DispatchCommand(CHAT_CLIENT_COMMAND_E enCmd)
{
    switch (enCmd)
    {
        case CHAT_CLIENT_CMD_LOGIN:
        {
            char szUser[CHAT_USER_MAXLEN + 1];
            char szPassword[CHAT_PASSWORD_MAXLEN + 1];
            __WaitInput("User", szUser, sizeof(szUser));
            __WaitInput("Password", szPassword, sizeof(szPassword));
            m_objSession.Login(szUser, szPassword);
            break;
        }

        case CHAT_CLIENT_CMD_LOGOUT:
        {
            char szUser[CHAT_USER_MAXLEN + 1];
            __WaitInput("User", szUser, sizeof(szUser));
            m_objSession.Logout(szUser);
            break;
        }

        case CHAT_CLIENT_CMD_REGISTER:
        {
            char szUser[CHAT_USER_MAXLEN + 1];
            char szPassword[CHAT_PASSWORD_MAXLEN + 1];
            __WaitInput("User", szUser, sizeof(szUser));
            __WaitInput("Password", szPassword, sizeof(szPassword));
            m_objSession.RegisterUser(szUser, szPassword);
            break;
        }

        case CHAT_CLIENT_CMD_EXIT:
        {
            m_bRunning = false;
            break;
        }
        
        default:
        {
            break;
        }
    }
}